<template>
  <div>
    <h1>讨论详情</h1>
    <h4>{{ discussion.user }} @ {{ discussion.date }}</h4>
    <p>{{ discussion.content }}</p>
    <img
      v-if="discussion.image"
      :src="discussion.image"
      alt="讨论图片"
      class="discussion-image"
    />

    <div class="button-container">
  <button @click="goBack" class="back-button">返回</button>
  <div class="like-section">
    <button @click="toggleLike">{{ liked ? "取消点赞" : "点赞" }}</button>
    <button @click="toggleFavorite">
      {{ favorite ? "取消收藏" : "收藏" }}
    </button>
    <span>{{ likeCount }} 人觉得不错</span>
  </div>

  <!-- 新增关注按钮 -->
  <button @click="followUser" class="follow-button">
    {{ isFollowing ? "取消关注" : "关注" }}
  </button>
</div>


    <div class="comments-section">
      <h3>评论区</h3>
      <div v-for="comment in comments" :key="comment.id" class="comment">
        <p>
          <strong>{{ comment.user }}:</strong> {{ comment.content }}
          <!-- 删除按钮替换点赞按钮 -->
          <button @click="deleteComment(comment)" class="delete-button">删除</button>
        </p>
      </div>

      <div class="comment-input">
        <input
          v-model="newComment"
          placeholder="添加评论..."
          @keyup.enter="addComment"
        />
        <button @click="addComment">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      isLoading: true,
      discussion: {},
      comments: [],
      newComment: "",
      likeCount: 0,
      liked: false,
      favorite: false,
      isFollowing: false,  // 记录当前是否关注该用户
      postId: null,
      studentId: 123, // 假设当前用户ID
      postUserId: null // 记录发帖人的 ID
    };
},

created() {
  const savedPost = localStorage.getItem('currentPost');
  
  if (savedPost) {
      this.discussion = JSON.parse(savedPost);
      this.postId = this.discussion.postId;
      this.postUserId = this.discussion.userId;  // 从 localStorage 获取发帖人的 ID
    } else {
      this.postId = this.$store.state.status.post_id;
      this.fetchDiscussionDetails(this.postId);
    }

    if (this.postId) {
      this.fetchComments(this.postId);
    }
},


  methods: {
    // 获取讨论详情
    async fetchDiscussionDetails(postId) {
  try {
    const response = await axios.get(`http://localhost:8085/posts/${postId}`);
    if (response.data) {
      const post = response.data;
      console.log("获取的帖子详情:", response.data);
      console.log("帖子用户ID:", post.userId);  // 确保这里返回了正确的 userId

      this.discussion = {
        postId: post.post_id,
        user: post.userId,  // 确保 userId 被正确赋值
        title: post.title,
        content: post.content,
        image: post.image_url || null,
        date: new Date(post.created_at).toLocaleString(),
        likeCount: post.like_count,
        liked: post.is_liked === 1,
        favorited: post.is_favorited === 1,
        studentId: post.student_id
      };
      this.postUserId = post.userId;
      console.log("讨论详情:", this.discussion);
    }
  } catch (error) {
    console.error("获取帖子详细信息失败:", error);
    alert("获取帖子详细信息失败，请稍后再试！");
  }
},

async followUser() {
  const followerNumber = this.$store.state.status.userId;  // 当前用户ID
  const followedNumber = this.discussion.userId;  // 帖子用户ID

  // 判断当前用户是否尝试关注自己
  if (followerNumber === followedNumber) {
    alert("不能关注自己！");
    return;  // 如果是自己，直接返回，避免发送请求
  }

  console.log("发送的数据:", {
    followerNumber: followerNumber,
    followedNumber: followedNumber
  });

  try {
    const response = await axios.post(
      `http://localhost:8085/follows/follow`,
      null,
      {
        params: {
          followerNumber: followerNumber,
          followedNumber: followedNumber
        }
      }
    );

    if (response.status === 200) {
      this.isFollowing = !this.isFollowing;  // 切换关注状态
      alert(this.isFollowing ? "关注成功" : "取消关注成功");
    }
  } catch (error) {
    console.error("关注失败:", error);
    alert("关注操作失败，请稍后再试！");
  }
},


    // 获取评论列表
    async fetchComments(postId) {
      try {
        const response = await fetch(`http://localhost:8085/comments?postId=${postId}`);
        if (!response.ok) {
          throw new Error("Failed to fetch comments");
        }
        const data = await response.json();
        this.comments = data; // 更新评论列表
      } catch (error) {
        console.error("Error fetching comments:", error);
      }
    },

    // 点赞功能
    toggleLike() {
      this.liked = !this.liked;
      this.likeCount += this.liked ? 1 : -1;
    },

    // 收藏功能
    toggleFavorite() {
      this.favorite = !this.favorite;
    },

    // 添加评论
    async addComment() {
  if (this.newComment.trim()) {
    const postId = this.postId;
    const studentId = this.$store.state.status.userId; // 从 Vuex 中获取学生ID
    const content = this.newComment.trim(); // 评论内容

    console.log(`Sending comment with postId=${postId}, studentId=${studentId}, content=${content}`);

    try {
      const response = await fetch(`http://localhost:8085/comments?postId=${postId}&studentId=${studentId}&content=${encodeURIComponent(content)}`, {
        method: 'POST',
      });

      const textResponse = await response.text();  // 获取响应内容作为文本

      try {
        const jsonResponse = JSON.parse(textResponse);
        console.log("Received comment data:", jsonResponse);

        // 添加新评论到评论列表，并确保每个评论的 ID 是唯一的
        this.comments.push(jsonResponse);

        // 清空评论输入框
        this.newComment = "";

        // 可选：重新获取评论列表以确保评论显示准确
         this.fetchComments(this.postId);  // 你也可以选择重新请求所有评论，来保证数据的一致性
       
      } catch (e) {
        console.log("Received non-JSON response:", textResponse);
        alert(textResponse);
      }

    } catch (error) {
      console.error("Error adding comment:", error);
      alert("评论发送失败，请检查网络连接。");
    }
  }
},

    // 删除评论
    async deleteComment(comment) {
      try {
        console.log("Deleting comment with ID:", comment.comment_id);
        const response = await fetch(`http://localhost:8085/comments/delete?commentId=${comment.comment_id}`, {
          method: 'POST'
        });

        if (!response.ok) {
          throw new Error("Failed to delete comment");
        }

        // 删除后刷新评论列表
        this.fetchComments(this.postId);
      } catch (error) {
        console.error("Error deleting comment:", error);
      }
    },

    // 返回上一页
    goBack() {
      this.$router.go(-1);
    }
  }
};
</script>
<style scoped>
/* 样式部分保持不变 */
</style>

<style scoped>
.follow-button {
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  background-color: #17a2b8;
  color: white;
  transition: background-color 0.3s;
}

.follow-button:hover {
  background-color: #138496;
}

.follow-button:focus {
  outline: none;
}

body {
  font-family: Arial, sans-serif;
  background-color: #f4f4f9;
  color: #333;
  margin: 0;
  padding: 20px;
}

h1 {
  color: #4a4a4a;
  font-size: 2em;
  margin-bottom: 10px;
}

h4 {
  color: #6c757d;
  margin-bottom: 20px;
}

p {
  line-height: 1.6;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.discussion-image {
  max-width: 100%;
  height: auto;
  border-radius: 5px;
  margin: 20px 0;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.button-container {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.back-button {
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  background-color: #007bff;
  color: white;
  transition: background-color 0.3s;
}

.back-button:hover {
  background-color: #0056b3;
}

.like-section {
  display: flex;
  align-items: center;
}

.like-section button {
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  background-color: #28a745;
  color: white;
  transition: background-color 0.3s;
  margin-left: 10px;
}

.like-section button:hover {
  background-color: #218838;
}

.comments-section {
  margin-top: 30px;
  padding: 15px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

h3 {
  margin-top: 0;
  color: #4a4a4a;
}

.comment {
  border-bottom: 1px solid #e0e0e0;
  padding: 10px 0;
}

.comment:last-child {
  border-bottom: none;
}

.comment-input {
  display: flex;
  margin-top: 10px;
}

.comment-input input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
  transition: border-color 0.3s;
}

.comment-input input:focus {
  border-color: #007bff;
  outline: none;
}

.comment-input button {
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  background-color: #007bff;
  color: white;
  transition: background-color 0.3s;
}

.comment-input button:hover {
  background-color: #0056b3;
}

.like-button {
  background-color: #ffc107;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 5px 10px;
  cursor: pointer;
  margin-left: 10px;
}

.like-button:hover {
  background-color: #e0a800;
}

.delete-button {
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 5px 10px;
  cursor: pointer;
  margin-left: 10px;
}

.delete-button:hover {
  background-color: #c82333;
}
</style>
